package com.work.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.work.dto.ProjectResourceDetailDTO;
import com.work.work.entity.Project;
import com.work.work.entity.ProjectResource;
import com.work.work.entity.Resource;
import com.work.work.mapper.ProjectMapper;
import com.work.work.mapper.ProjectResourceMapper;
import com.work.work.mapper.ResourceMapper;
import com.work.work.service.ResourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProjectResourceMapper projectResourceMapper;
    @Override
    public Page<Resource> getResourcesByProjectId(Integer projectId, Integer current, Integer size) {
        // 通过中间表查询
        return baseMapper.selectResourcesByProjectId(projectId, new Page<>(current, size));
    }

    @Override
    public Page<Resource> getResourcesByType(String resourceType, Integer current, Integer size) {
        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resource::getResourceType, resourceType);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductResourceQuantity(Integer resourceId, BigDecimal quantity) {
        Resource resource = getById(resourceId);
        if (resource == null) {
            throw new RuntimeException("资源不存在");
        }

        if (resource.getQuantity().compareTo(quantity) < 0) {
            throw new RuntimeException("资源数量不足");
        }

        resource.setQuantity(resource.getQuantity().subtract(quantity));
        return updateById(resource);
    }
    @Override
    public ProjectResourceDetailDTO getProjectResourceDetail(Integer projectId) {
        // 获取项目基本信息
        ProjectResourceDetailDTO projectDetail = baseMapper.getProjectDetail(projectId);
        if (projectDetail == null) {
            throw new RuntimeException("项目不存在");
        }

        // 获取项目资源列表
        List<ProjectResourceDetailDTO.ResourceUsage> resources = baseMapper.getProjectResources(projectId);
        projectDetail.setResources(resources);

        return projectDetail;
    }

}